<template>
  <el-form :model="form" label-width="auto" style="max-width: 700px;margin: auto;">
 
     <el-form-item label="姓名:">
       <el-input v-model="form.userName" />
     </el-form-item>
     
     <el-form-item label="部门:">
       <el-select v-model="form.departmentId" placeholder="请选择部门">
         <el-option label="IT信息部" :value="1" />
         <el-option label="人力资源部" :value="2" />
         <el-option label="财务部" :value="3" />
         <el-option label="销售部" :value="4" />
         <el-option label="行政部" :value="5" />
       </el-select>
     </el-form-item>
 
     <el-form-item label="请假类别:">
       <el-checkbox-group v-model="form.LeaveType" >  
       <el-checkbox   v-for="item in leaveTypes" :key="item.value" :value="item.value" @change="handleCheckboxChange(item.value)"  >  
         {{ item.label }}  
       </el-checkbox>  
     </el-checkbox-group>  
     </el-form-item>
 
     <el-form-item label="请假时间:">
 
         <el-date-picker v-model="form.leaveStartTime" type="datetime" placeholder="请假开始时间" format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD h:m:s"/>
         至<el-date-picker v-model="form.leaveEndTime" type="datetime" placeholder="请假结束时间" format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD h:m:s"/>
 
         共计<el-input v-model="getDate[0]" style="width: 70px;" ></el-input>天    
         <el-input v-model="getDate[1]" style="width: 70px;" ></el-input>时  
 
         报到时间:<el-date-picker v-model="form.registrationTime" type="datetime" placeholder="请选择报到时间" format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD h:m:s"/>
     </el-form-item>
 
     <el-form-item label="请假事由">
       <el-input v-model="form.subjectMatter" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea" placeholder="请输入请假事由" show-word-limit maxlength="140"/>
     </el-form-item>
 
     <el-form-item label="部门领导">
       <el-select v-model="form.departmentLeader">
         <el-option label="请选择" :value="0"></el-option>
         <el-option v-for="item in userInfo" :key="item.userId" :value="item.userName" :label="item.userName"></el-option>
       </el-select>
     </el-form-item>
 
     <el-form-item label=" ">
       <el-button type="primary" @click="onSubmit">修改</el-button>
     </el-form-item>
   </el-form>
 </template>
 
 <script setup lang="ts">
 import { reactive, ref, onMounted, computed } from 'vue'
 import axios from 'axios';
 import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
 import { ElMessage, ElMessageBox } from 'element-plus'
 
 import {useRoute,useRouter} from 'vue-router'
 
 const route = useRoute();
 const router = useRouter();
 
 onMounted(() => {
  BackLeave()
 })
const form: any = reactive({
   leaveId:route.query.leaveId,
   userName: '',
   departmentId: '',
   leaveStartTime: '',
   leaveEndTime:'',
   totalDays: '',
   totalHours: '',
   totalWorkTime: '',
   registrationTime: '',
   subjectMatter: '',
   departmentLeader: '',
  userId: '',
  LeaveType:[]
 })
 
 //const LeaveType:any=ref([])
 
 //请假类别数组
 const leaveTypes: any = ref([
   {value:1,label:'事假'},  
   {value:2,label:'病假'},  
   {value:3,label:'婚假'},  
   {value:4,label:'丧假'},  
   {value:5,label:'产假'},  
   {value:6,label:'补休'},  
   {value:7,label:'工伤'},  
   {value:8,label:'其他'}  
 ])
 
 const handleCheckboxChange = (newValue: any) => {
   // 清空之前选中的值  
   form.LeaveType.value = [newValue];
   console.log(form.LeaveType);
   console.log(form.LeaveType.value);
 };
 
 const getDate:any = computed(() => {
   if (!form.leaveStartTime || !form.leaveEndTime) {
     return 0;
   }
 
   const start = new Date(form.leaveStartTime);
   const end = new Date(form.leaveEndTime);
   const diffMs = end.getTime() - start.getTime();
   const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
   const diffHours = Math.floor(diffMs % (1000 * 60 * 60 * 24) / (1000 * 60 * 60));
   // console.log(diffDays);
   // console.log(diffHours);
   form.totalDays = diffDays;
   form.totalHours = diffHours;
   return [diffDays,diffHours]
 })
 
 //获取Token字符串中的UserId
 var token:any = localStorage.getItem("Tokens")
 //console.log(token);
 //分割JWT字符串
 const [header, payload, signature] = token.split(".");
 //Base64解码Payload
 const payloadDecoded = atob(payload);
 //解析JSON字符串
 const payloadParsed=JSON.parse(payloadDecoded)
 //提取userId和roleId
 form.userId = payloadParsed.sub;
 const roleId = payloadParsed['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'];  
 // console.log(form.userId);
 // console.log(roleId);
 
 //反填请假信息
const BackLeave = () => {
  let leaveData = {
    leaveId: form.leaveId
  }
  axios.post('/api/LeaveManagement/ReverseLeaveInfo', leaveData).then(res => {
    console.log(res);
    const leaveInfo = res.data.data;
    //console.log(leaveInfo);
    form.userName = leaveInfo.userName;
    form.departmentId = leaveInfo.departmentId;
    let leaveTypeNumber = leaveInfo.leaveType;
    // console.log(leaveTypeNumber);

    form.LeaveType = [Number(leaveTypeNumber)]
    // console.log( form.LeaveType);
    
    form.leaveStartTime = leaveInfo.leaveStartTime;
    form.leaveEndTime = leaveInfo.leaveEndTime;

    form.totalDays = leaveInfo.totalDays;
    form.totalHours = leaveInfo.totalHours;

    form.totalWorkTime = leaveInfo.totalWorkTime;

    form.registrationTime = leaveInfo.registrationTime;
    
    form.subjectMatter = leaveInfo.subjectMatter;
    form.departmentLeader = leaveInfo.departmentLeader;
    let id = leaveInfo.departmentId;
    getUserInfoByDepartmentId(id)
  }).catch(err => {
    console.log(err);

  })
}
 //通过部门ID查询用户信息
 const userInfo:any=ref([])
 const getUserInfoByDepartmentId = (departmentId:number) => {   
   let departData = {
     departmentId:departmentId 
   }
   axios.post('/api/LeaveManagement/GetUserInfoByDepartmentId',departData).then(res=>{
     //console.log(res);
     userInfo.value = res.data.data;
   }).catch(err=>{
     console.log(err);
     
   }) 
 }
 
 //修改申请
 const onSubmit = () => {
   let totalWorkTime = (form.totalDays * 24 / 3) + form.totalHours
   let typeId = form.LeaveType[0];
   console.log(typeId);
   
   let updateLeave = {
     leaveId:form.leaveId,
     userName: form.userName,
     departmentId: form.departmentId,
     leaveStartTime:form.leaveStartTime,
     leaveEndTime: form.leaveEndTime,
     LeaveType: form.LeaveType[0],
     totalWorkTime: totalWorkTime,
     registrationTime: form.registrationTime,
     subjectMatter: form.subjectMatter,
     departmentLeader:form.departmentLeader,
   }
   //console.log(form.LeaveType.value[0]);
   
   axios.post('/api/LeaveManagement/UpdateLeaveInfo',updateLeave).then(res=>{
     console.log(res);
     if (res.data.code >= 0) {
       ElMessage.success("修改成功!")
       router.push('LeaveList')
     } else {
       ElMessage.error("修改失败!")
       return
     }
   }).catch(err=>{
     console.log(err);
     
   }) 
 }
 
 </script>
 
 <style scoped>
 
 .input-container .el-input__inner,  
 .input-container .el-date-picker__editor .el-input__inner {  
   border-bottom: 2px solid #dcdfe6; /* 自定义下划线样式 */  
   border-top: none;  
   border-left: none;  
   border-right: none;  
   border-radius: 0;  
   padding: 0 10px;  
 }  
   
 .input-container .el-form-item__label {  
   font-weight: bold; /* 可选：加粗标签文本 */  
 }  
 
 </style>